<?php

namespace backend\controllers;

use backend\models\JjrUserProject;
use Yii;
use backend\models\JjrUser;
use backend\models\JjrUserSearch;
use backend\controllers\BaseController;
use yii\db\Exception;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use SimpleExcel\SimpleExcel;
use yii\web\UploadedFile;

/**
 * JjrUserController implements the CRUD actions for JjrUser model.
 */
class JjrUserController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all JjrUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new JjrUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JjrUser model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new JjrUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JjrUser();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing JjrUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing JjrUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $userProject = JjrUserProject::findOne(['jjr_user_id'=>$id]);
        if($userProject){
            $this->error("删除失败,该经纪人已存在客户");
        }
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the JjrUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return JjrUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JjrUser::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionAudit($id){
        $model =$this->findModel($id);
        $model->updateAttributes(['status'=>1]);
        return $this->redirect(['index']);
    }
    public function actionCancelAudit($id){
        $model =$this->findModel($id);
        $model->updateAttributes(['status'=>0]);
        return $this->redirect(['index']);
    }

    /**
     * 下载模板
     */
    public function actionDownload(){
        $res = \YII::$app->response;
        $res->sendFile(Yii::getAlias('@base/web/storage/tpl/import.csv'));
    }

    /**
     * excel导出
     */
    public function actionExport(){
        require_once('../../vendor/SimpleExcel/SimpleExcel.php');
        $excel = new SimpleExcel('CSV');
        $excel->writer->setDelimiter(",");
        $query = JjrUser::find();
        $query->alias('u1')->leftJoin('yii2_jjr_user u2','u1.fuid=u2.id')
            ->select('u1.*,u2.real_name as invitor')->asArray();
        $users = $query->all();
        $exportUsers = [array (
            'id',
            '真实姓名',
            '手机号码',
            '身份类型',
            '身份证号码',
            '注册时间',
            '推荐人',
            '邀请码',
            '状态'
        )];
        foreach ($users as $user){
            $identity = $user['identity']==1?'自由经纪人':'公司经纪人';
            $status = $user['status']==0?'未审核':'已审核';
            $tmp = [$user['id'],$user['real_name'],$user['mobile']."\t",$identity,$user['idcard']."\t",$user['create_time'],$user['invitor'],$user['invite_code']."\t",$status];
            $exportUsers[] = $tmp;
        }

        $excel->writer->setData (
            $exportUsers);

        $excel->writer->saveFile ( '导出经纪人' );

    }

    /**
     * excel导入
     * @throws Exception
     */
    public function actionImport(){
       // echo __FILE__;exit;
        require_once('../../vendor/SimpleExcel/SimpleExcel.php');
        $excel = new SimpleExcel('CSV');
        $attachment = UploadedFile::getInstanceByName("attachment_3");

        if($attachment){
            $path = Yii::getAlias('@base/web/storage/file/').date("Ym");
            $newFileName = $path.'/'.date("YmdHis").'.'.$attachment->getExtension();
          if (!file_exists($path)) {
             mkdir($path, 0777,true);
                      chmod($path, 0777);
            }
            $attachment->saveAs($newFileName);
            $excel->parser->loadFile($newFileName);
            $users = [];
            $errorUsers = [];
            for($i=2;$i<=50;$i++){
                if(!$excel->parser->isRowExists($i)){
                    break;
                }
                $row = $excel->parser->getRow($i);
                $jump = true;
                foreach($row as $col){
                    if(!empty($col)){
                        $jump = false;
                    }
                }
                if($jump){
                    continue;
                }
                $user = new JjrUser();

                $user->real_name = isset($row[0])?mb_convert_encoding($row[0], "UTF-8", "GBK"):null;
                $user->mobile = isset($row[1])?$row[1]:null;
                $user->password = isset($row[2])?$row[2]:null;
                $user->idcard = isset($row[3])?$row[3]:null;
                if( isset($row[4])){
                    $row[4] = mb_convert_encoding($row[4], "UTF-8", "GBK");
                    if($row[4]=='男'){
                        $user->gender = 1;
                    }else if($row[4]=='女'){
                        $user->gender = 2;
                    }else{
                        $user->gender = 3;
                    }
                }else{
                    $user->gender = null;
                }
                $user->identity = JjrUser::IDENTITY_COMPANY;
                $user->openid = 'unset';
                $user->status =1;
                if($user->validate()){
                    $users[] = $user;
                }else{

                    $errorUsers[$i] = $user;
//                    $errors = [];
//                    foreach ($user->getErrors() as $error){
//                        array_push($errors,implode('',$error));
//                    }
//                    echo "第{$i}行错误：". implode('',$errors),"\n";

                }
            }
            if(count($users)>0&&count($errorUsers)==0){
                $transaction=Yii::$app->db->beginTransaction();
                try{
                    foreach ($users as $user){
                        $user->save();
                    }
                    $transaction->commit();
                }catch (Exception $e) {
                    $transaction->rollBack();
                }
                echo "上传成功,请刷新页面查看";
            }else{
                foreach ($errorUsers as $row=>$user){
                    $errors = [];
                    foreach ($user->getErrors() as $error){
                        array_push($errors,implode('',$error));
                    }
                    echo "第{$row}行错误：". implode(';',$errors),"\n";
                }
            }


             exit;
            //print_r($row);exit;
        }


        print_r($excel);exit;


    }
}
